<?php
namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\MachineAbImages;
use Dingo\Api\Http\Request;
use Illuminate\Support\Facades\DB;


class MachineAbImagesController extends Controller
{
    protected $model;

    public function __construct(MachineAbImages $machineabimages)
    {
        $this->model = $machineabimages;
    }


    public function getMachineimg(Request $request)
    {  
        $domain = "http://".$_SERVER['HTTP_HOST'];   
        $machineId = $request->machineId;
        $machineinfo = DB::table('machines')->where('id', '=', $machineId)->select('title')->first();
        $result = $this->model->where('machine_id',$machineId)->get();
        //查询默认图片表数据
        $default_imgs = DB::table('adver_images')->select('adver_image')->get()->toArray();
        $default_imgs_arr = array_column($default_imgs,'adver_image');
        $default_imgs_num = count($default_imgs_arr);
        $round_default_imgs_arr = [];
        $data= [];
        $check_default_img = function($rarr, $arr) use (&$check_default_img){
            
            //先在默认图片中随机一个,与前一个随机元素不重复则添加
            $default_img_path = array_rand($arr);
            if(!array_search($default_img_path, $rarr)){  
                array_push($rarr,$default_img_path);
                return $default_img_path;                           
            }else{
                $check_default_img($rarr,$arr);
            }
        };

        if(!$result->isEmpty()){
            foreach ($result as $k => $v){
                if($v->available_time != NULL){
                    $data['date'][$k]['image'] = ($v->host).($v->path);
                    $data['date'][$k]['url'] = $v->out_url == 'null' ? 0 : $v->out_url;   
                }else{
                    //当广告图片数据大于默认图片数量时不再处理
                    if($k < $default_imgs_num){
                        $path_index = $check_default_img($round_default_imgs_arr,$default_imgs_arr);
                        $data['date'][$k]['image'] = $domain.$default_imgs_arr[$path_index];
                        $data['date'][$k]['url'] = $v->out_url == NULL ? 'null' : $v->out_url; 
                    }
                }
            } 
        }else{
            foreach($default_imgs_arr as $k=>$v){
                $data['date'][$k]['image'] = $domain.$v;
                $data['date'][$k]['url'] = 'null'; 
            }
        }
        $newData['data'] = array_values($data['date']);
        $newData['title'] = $machineinfo->title;
        return $this->success($newData);

    }


}